﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using TaxAssistantBase;

namespace ShiBieProject
{
    class AmountAndDetailsEtcMoney
    {
        private static string [] taxRateList = { "0%", "3%","4%","5%","6%","9%","10%","11%","13%","16%","17%","18%"};
        public static void moneyChuLi(List<InvoiiceOcrModel> bpmlist)
        {
            foreach (InvoiiceOcrModel bpm in bpmlist) {
                if (bpm.billtype!=-1 && (bpm.invoiceOcrSonListSet[0].readstate == "4" || bpm.invoiceOcrSonListSet[0].readstate == "3" || bpm.invoiceOcrSonListSet[0].readstate == "2")) {
                    if (bpm.invoiceOcrSonLists != null && bpm.invoiceOcrSonLists.Count > 0)
                    {
                        string money = bpm.invoiceOcrSonLists[0].moneyAmounts;
                        string moneytaxhj = bpm.invoiceOcrSonLists[0].totalMoney;
                        string taxmoney = bpm.invoiceOcrSonLists[0].taxAmounts;
                        string taxlv = bpm.invoiceOcrSonLists[0].taxRate;
                        string invoicetype = bpm.invoiceOcrSonLists[0].invoicetype;
                        string invoiceNum = bpm.invoiceOcrSonLists[0].invoiceNum;
                        string moneyTotleMax = bpm.invoiceOcrSonLists[0].moneytaxhjMax;//金额大写
                        if (string.IsNullOrEmpty(invoicetype))
                        {
                            bpm.invoiceOcrSonLists[0].invoicetypeState = CompanyOrMoneyStateEnum.InvoiceTypeIncorrect;
                        }
                        else if (invoicetype != "普票" && invoicetype != "专票")
                        {
                            bpm.invoiceOcrSonLists[0].invoicetypeState = CompanyOrMoneyStateEnum.InvoiceTypeIncorrect;
                        }
                        if (string.IsNullOrEmpty(invoiceNum))
                        {
                            bpm.invoiceOcrSonLists[0].invoiceNumState = CompanyOrMoneyStateEnum.InvoiceNumIncorrect;
                        }
                        else if (invoiceNum.Length != 8)
                        {
                            bpm.invoiceOcrSonLists[0].invoiceNumState = CompanyOrMoneyStateEnum.InvoiceNumIncorrect;
                        }
                        if (taxlv != null)
                        {
                            if (getTaxRate(taxlv))
                            {
                                taxlv = "0%";
                                taxmoney = "0";
                                bpm.invoiceOcrSonLists[0].taxRate = "0%";
                                bpm.invoiceOcrSonLists[0].taxAmounts = "0";
                            }
                            else if (taxlv.Contains("*"))
                            {
                                taxlv = "空";
                            }
                        }
                        if (CheackIsNullOrEmpty(money, taxmoney, moneytaxhj))
                        {
                            bpm.invoiceOcrSonLists[0].totalStateMoney = CompanyOrMoneyStateEnum.MoneyIsNullIncorrect;
                        }
                        else
                        {
                            decimal moneyes;
                            decimal taxmoneyes;
                            decimal moneytaxhjes;
                            //2.个别不存在
                            //2.1如果金额为空其他不为空
                            if ((string.IsNullOrEmpty(money)) && (!string.IsNullOrEmpty(taxmoney)) && (!string.IsNullOrEmpty(moneytaxhj)))
                            {
                                decimal.TryParse(taxmoney, out taxmoneyes); decimal.TryParse(moneytaxhj, out moneytaxhjes);
                                moneyes = Math.Round((moneytaxhjes - taxmoneyes), 2, MidpointRounding.AwayFromZero);
                                bpm.invoiceOcrSonLists[0].moneyAmounts = Convert.ToString(moneyes);
                                money = Convert.ToString(moneyes);
                                bpm.invoiceOcrSonLists[0].moneyAmountsState = CompanyOrMoneyStateEnum.MoneyManualCalculation;
                            }    //2.2如果税额为空其他不为空
                            else if ((!string.IsNullOrEmpty(money)) && (string.IsNullOrEmpty(taxmoney)) && (!string.IsNullOrEmpty(moneytaxhj)))
                            {
                                decimal.TryParse(money, out moneyes); decimal.TryParse(moneytaxhj, out moneytaxhjes);
                                taxmoneyes = Math.Round((moneytaxhjes - moneyes), 2, MidpointRounding.AwayFromZero);
                                if (taxmoneyes != null) {
                                    bpm.invoiceOcrSonLists[0].taxAmounts = Convert.ToString(taxmoneyes);
                                }
                                taxmoney = Convert.ToString(taxmoneyes);
                                bpm.invoiceOcrSonLists[0].taxAmountsState = CompanyOrMoneyStateEnum.MoneyManualCalculation;
                            } //    //2.4如果价税合计为空其他不为空
                            else if ((!string.IsNullOrEmpty(money)) && (!string.IsNullOrEmpty(taxmoney)) && (string.IsNullOrEmpty(moneytaxhj)))
                            {
                                decimal.TryParse(money, out moneyes); decimal.TryParse(taxmoney, out taxmoneyes);
                                moneytaxhjes = Math.Round((moneyes + taxmoneyes), 2, MidpointRounding.AwayFromZero);
                                bpm.invoiceOcrSonLists[0].totalMoney = Convert.ToString(moneytaxhjes);
                                moneytaxhj = Convert.ToString(moneytaxhjes);
                                bpm.invoiceOcrSonLists[0].totalMoneyState = CompanyOrMoneyStateEnum.MoneyManualCalculation;
                            } else if (!string.IsNullOrEmpty(moneyTotleMax)) {
                                if (moneyTotleMax.Contains("角") || moneyTotleMax.Contains("分"))
                                {
                                    Regex reg = new Regex(@"^\d+\.\d+$");
                                    if (!reg.IsMatch(moneytaxhj))
                                    {
                                        bpm.invoiceOcrSonLists[0].totalStateMoney = CompanyOrMoneyStateEnum.MxMoneyNotEqualToMoney;
                                    }
                                    else
                                    {
                                        string pointout = moneytaxhj.Split('.')[1];
                                        if (pointout == "00" || pointout == "0" || pointout == "000")
                                        {
                                            bpm.invoiceOcrSonLists[0].totalStateMoney = CompanyOrMoneyStateEnum.MxMoneyNotEqualToMoney;
                                        }
                                    }
                                }
                            } else if (!string.IsNullOrEmpty(moneytaxhj) && !string.IsNullOrEmpty(taxmoney)) {
                                //2.8如果合计和税额为空其他不为空
                                decimal.TryParse(taxmoney, out taxmoneyes); decimal.TryParse(moneytaxhj, out moneytaxhjes);
                                moneyes = Math.Round((moneytaxhjes + taxmoneyes), 2, MidpointRounding.AwayFromZero);
                                bpm.invoiceOcrSonLists[0].totalMoney = Convert.ToString(moneyes);
                            }
                            else if (!string.IsNullOrEmpty(moneytaxhj) && !string.IsNullOrEmpty(money))
                            {
                                //    //2.9如果合计和金额为空其他不为空
                                decimal.TryParse(money, out moneyes); decimal.TryParse(moneytaxhj, out moneytaxhjes);
                                taxmoneyes = Math.Round((moneytaxhjes - moneyes), 2, MidpointRounding.AwayFromZero);
                                bpm.invoiceOcrSonLists[0].taxAmounts = Convert.ToString(taxmoneyes);
                            }
                        }
                        decimal moneye = 0;
                        decimal taxmoneye = 0;
                        decimal moneytaxhje = 0;
                        string taxendrate = "";
                        //将价税合计转化成繁体汉字形态
                        string ChinaNum = ToRMB(moneytaxhj);
                        if (ChinaNum != null && ChinaNum != "")
                        {
                            //比对大写汉字金额与价税合计是否一致
                            if (ChinaNum == moneyTotleMax)
                            {
                                taxendrate = gettaxrate(money, moneytaxhj, bpm.invoiceOcrSonLists[0]);
                            }
                        }
                        if (decimal.TryParse(money, out moneye) && (decimal.TryParse(taxmoney, out taxmoneye)))
                        {
                            string resaulttaxlv = calculatingTaxRate(moneye, taxmoneye);
                            if (string.IsNullOrEmpty(taxlv))
                            {
                                bpm.invoiceOcrSonLists[0].taxRate = resaulttaxlv;
                                bpm.invoiceOcrSonLists[0].taxRateState = CompanyOrMoneyStateEnum.MoneyManualCalculation;
                            }
                            else if (resaulttaxlv != taxlv)
                            {

                                if (resaulttaxlv == "" || resaulttaxlv == null)
                                {
                                    if (taxlv != "" && taxlv != null)
                                    {
                                        if (taxlv == "免税" || taxlv.Contains("税") || taxlv.Contains("免")|| !IsNumber(taxlv))
                                        {
                                            bpm.invoiceOcrSonLists[0].taxRate = "0%";
                                            bpm.invoiceOcrSonLists[0].taxAmounts = "0";
                                        }
                                        else if (taxlv.Contains("*"))
                                        {
                                            bpm.invoiceOcrSonLists[0].taxRate = "";
                                        } else if (taxendrate != null&& taxendrate != "") {
                                            bpm.invoiceOcrSonLists[0].taxRate = taxendrate;
                                        }
                                        else {
                                            decimal taxratedec;
                                            string taxrate = taxlv.Replace("%", "");
                                            string temptaxrate = "";
                                            decimal.TryParse(taxrate, out taxratedec);
                                            decimal endtaxratedec = Math.Round(taxratedec, 2, MidpointRounding.AwayFromZero);// MidpointRounding.ToEven
                                            temptaxrate = InvoiceOcrTool.setTaxLv(endtaxratedec);
                                            if (temptaxrate != "" && temptaxrate != null)
                                            {
                                                bpm.invoiceOcrSonLists[0].taxRate = temptaxrate;
                                            }
                                            else
                                            {
                                                taxrate = getLikeTaxRate(taxrate);//获取模糊税率
                                                bpm.invoiceOcrSonLists[0].taxRate = taxrate;
                                            }

                                        }

                                    } else {
                                        string taxrae = "";
                                        foreach (string taxr in taxRateList) {
                                            if (bpm.invoiceOcrSonLists[0].taxRate == taxr) {
                                                taxrae = taxr; 
                                            }
                                        }
                                        bpm.invoiceOcrSonLists[0].taxRate = taxrae;
                                    }
                                }
                                else {
                                    bpm.invoiceOcrSonLists[0].taxRate = resaulttaxlv;
                                }
                                bpm.invoiceOcrSonLists[0].taxRateState = CompanyOrMoneyStateEnum.MoneyManualCalculation;
                            }
                        }
                        if ((!decimal.TryParse(money, out moneye)) || (!decimal.TryParse(taxmoney, out taxmoneye)) || (!decimal.TryParse(moneytaxhj, out moneytaxhje)))
                        {
                            bpm.invoiceOcrSonLists[0].totalStateMoney = CompanyOrMoneyStateEnum.MoneyGeShiIncorrect;
                            continue;
                        }
                        decimal mxmoneyTotle = 0;
                        decimal mxtaxmoneyTotle = 0;
                        //处理明细
                        if (bpm.invoiceOcrDetailedDtoList != null && bpm.invoiceOcrDetailedDtoList.Count > 0)
                        {
                     //       bool isRight = invoiceDetailVserificationMoneyEtc.detailVserification(bpm.invoiceOcrDetailedDtoList, out mxmoneyTotle, out mxtaxmoneyTotle);
                            //if (!isRight)
                            //{
                            //    bpm.invoiceOcrSonLists[0].totalStateMoney = CompanyOrMoneyStateEnum.MxMoneyOcrNoRight;
                            //    continue;
                            //}
                        }
                        if (mxmoneyTotle != moneye && mxtaxmoneyTotle == taxmoneye)
                        {
                            if (!moneyCalculationIsbalance(moneye, taxmoneye, moneytaxhje))
                            {
                                //暂时判定为金额错误
                                bpm.invoiceOcrSonLists[0].moneyAmounts = Convert.ToString(Math.Round((moneytaxhje - taxmoneye), 2, MidpointRounding.AwayFromZero));
                                bpm.invoiceOcrSonLists[0].moneyAmountsState = CompanyOrMoneyStateEnum.MoneyManualCalculation;
                                continue;
                            }
                        }
                        if (mxmoneyTotle == moneye && mxtaxmoneyTotle != taxmoneye)
                        {
                            if (!moneyCalculationIsbalance(moneye, taxmoneye, moneytaxhje))//判断金额+税额是否等于合计
                            {
                                //暂时判定为税额错误
                                if (Convert.ToString(Math.Round((moneytaxhje - moneye), 2, MidpointRounding.AwayFromZero))!=null && Convert.ToString(Math.Round((moneytaxhje - moneye), 2, MidpointRounding.AwayFromZero))!="") {
                                    bpm.invoiceOcrSonLists[0].taxAmounts = Convert.ToString(Math.Round((moneytaxhje - moneye), 2, MidpointRounding.AwayFromZero));
                                }
                               
                                bpm.invoiceOcrSonLists[0].taxAmountsState = CompanyOrMoneyStateEnum.MoneyManualCalculation;
                                continue;
                            }
                        }
                        else if (mxmoneyTotle != moneye && mxtaxmoneyTotle == taxmoneye)
                        {
                            if (!moneyCalculationIsbalance(moneye, taxmoneye, moneytaxhje))//判断金额+税额是否等于合计
                            {
                                //暂时判定为金额错误
                                bpm.invoiceOcrSonLists[0].moneyAmounts = Convert.ToString(Math.Round((moneytaxhje - taxmoneye), 2, MidpointRounding.AwayFromZero));
                                bpm.invoiceOcrSonLists[0].moneyAmountsState = CompanyOrMoneyStateEnum.MoneyManualCalculation;
                                continue;
                            }
                        }
                        else if (mxmoneyTotle != moneye || mxtaxmoneyTotle != taxmoneye)
                        {
                            bpm.invoiceOcrSonLists[0].totalStateMoney = CompanyOrMoneyStateEnum.MxMoneyNotEqualToMoney;
                            continue;
                        }
                        //2.校验是否平
                        if (!moneyCalculationIsbalance(moneye, taxmoneye, moneytaxhje))
                        {
                           // bpm.invoiceOcrSonLists[0].totalMoney = Convert.ToString(Math.Round((moneye + taxmoneye), 2, MidpointRounding.AwayFromZero));
                            bpm.invoiceOcrSonLists[0].totalMoneyState = CompanyOrMoneyStateEnum.MoneyManualCalculation;
                            bpm.invoiceOcrSonLists[0].totalStateMoney = CompanyOrMoneyStateEnum.MoneyOcrNoRight;
                            continue;
                        }
                        bpm.invoiceOcrSonLists[0].totalStateMoney = CompanyOrMoneyStateEnum.MoneyCalculationAbsolutelyRight;
                        continue;
                    }
                }
             
            }
        }
        /// <summary>
        /// 根据税率是否等于免税，不征税等字样半段是否为0%
        /// </summary>
        /// <param name="taxRate"></param>
        /// <returns></returns>
        public static bool getTaxRate(string taxRate)
        {
            if (!string.IsNullOrEmpty(taxRate))
            {
                if (taxRate.Contains("免税") || taxRate.Contains("免") || taxRate.Contains("税"))
                {
                    return true;
                }
                else if (taxRate.Contains("不征税") || taxRate.Contains("不") || taxRate.Contains("征"))
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 判断字符串是否是数字
        /// </summary>
        public static bool IsNumber(string money)
        {
            const string pattern = "^[0-9]*$";
            Regex rx = new Regex(pattern);
            return rx.IsMatch(money);
        }

        public static string gettaxrate(string money,string moneytaxhj,InvoiceSonModel invoiceSonModel)
        {
            string taxendrate = "";
            decimal moneyes;
            decimal moneytaxhjes;
            decimal.TryParse(money, out moneyes); decimal.TryParse(moneytaxhj, out moneytaxhjes);
            decimal temptaxmoney = Math.Round((moneytaxhjes - moneyes), 2, MidpointRounding.AwayFromZero);
            taxendrate = calculatingTaxRate(moneyes, temptaxmoney);
            invoiceSonModel.taxAmounts = Convert.ToString(temptaxmoney);
            return taxendrate;
        }
        public static string ToRMB(object value)
        {
            try
            {
                string hash = double.Parse(value.ToString()).ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A");
                string results = Regex.Replace(hash, @"((?<=-|^)[^1-9]*)|((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L.]|$))))|((?'b'[F-L])(?'z'0)[0A-L]*((?=[1-9])|(?'-z'(?=[.]|$))))", "${b}${z}");
                hash = Regex.Replace(results, ".", delegate (Match m) { return "负圆空零壹贰叁肆伍陆柒捌玖空空空空空空空分角拾佰仟万億兆京垓秭穰"[m.Value[0] - '-'].ToString(); });
                if (!string.IsNullOrEmpty(hash))
                {
                    if (hash.Substring(hash.Length - 1, 1) == "圆") { hash += "整"; }
                    return hash;
                }
                else {
                    return "零";
                }
            }
            catch (Exception)
            {
                return "零";
            }
        }
        public static string getLikeTaxRate(string taxlv) {
            string endTaxRate = "";
            if (taxlv.Contains("3"))
            {
                endTaxRate = "3%";
            }
            else if (taxlv.Contains("5"))
            {
                endTaxRate = "5%";
            }
            else if (taxlv.Contains("6"))
            {
                endTaxRate = "6%";
            }
            else if (taxlv.Contains("9"))
            {
                endTaxRate = "9%";
            }
            else if (taxlv.Contains("10"))
            {
                endTaxRate = "10%";
            }
            else if (taxlv.Contains("11"))
            {
                endTaxRate = "11%";
            }
            else if (taxlv.Contains("13"))
            {
                endTaxRate = "13%";
            }
            else if (taxlv.Contains("16"))
            {
                endTaxRate = "16%";
            }
            else {
                endTaxRate = "";
            }
            return endTaxRate;
        }
        /// <summary>
        /// 手动算税率
        /// </summary>
        /// <param name="money"></param>
        /// <param name="taxmoney"></param>
        /// <returns></returns>
        public static string calculatingTaxRate(decimal moneye, decimal taxmoneye) {
            string taxlvend="";
                if (moneye!=0&& taxmoneye!=0) {
                decimal shulv = Math.Round((taxmoneye / moneye), 2, MidpointRounding.AwayFromZero) * 100;
                 taxlvend = InvoiceOcrTool.setTaxLv(shulv);
            }
            
                return taxlvend;
        }
        /// <summary>
        /// 计算金额是否平衡
        /// </summary>
        /// <param name="money"></param>
        /// <param name="taxmoney"></param>
        /// <param name="totalmoeny"></param>
        /// <returns></returns>
        private static bool moneyCalculationIsbalance(decimal moneye, decimal taxmoneye, decimal totalmoneye) {
                decimal zongjine = Math.Round((moneye + taxmoneye), 2, MidpointRounding.AwayFromZero);
            if (zongjine == totalmoneye)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 金额等是否为空
        /// </summary>
        /// <param name="money"></param>
        /// <param name="taxlv"></param>
        /// <param name="taxmoney"></param>
        /// <param name="totalmoeny"></param>
        /// <returns></returns>
        private static bool CheackIsNullOrEmpty(string money,string taxmoney,string totalmoeny ) {
            if ((string.IsNullOrEmpty(money))|| (string.IsNullOrEmpty(taxmoney))|| (string.IsNullOrEmpty(totalmoeny))) {
                return true;
            }
            return false; 
        }
    }
}
